﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using MN.Framework.Common;
using MN.Framework.Extensions;

namespace Mn.Framework.Web.Mvc
{
    public abstract class MnEntityController<TEntityType> : Controller where TEntityType : BaseEntity
    {
        public abstract BaseContext DbContext
        {
            get;
        }


        public virtual ActionResult Grid_Read([DataSourceRequest]DataSourceRequest request)
        {
            DbContext.Configuration.LazyLoadingEnabled = false;
            var jsonRes = Json(DbContext.Set<TEntityType>().ToDataSourceResult(request),
                JsonRequestBehavior.AllowGet);
            return jsonRes;

        }
        public virtual ActionResult Grid_Read_Detail([DataSourceRequest]DataSourceRequest request, string propertyName, int value)
        {
            DbContext.Configuration.LazyLoadingEnabled = false;
            var jsonRes = Json(DbContext.Set<TEntityType>().AsEnumerable().Where(propertyName + "=" + value.ToString()).ToList()
                .ToDataSourceResult(request),
                JsonRequestBehavior.AllowGet);
            return jsonRes;

        }
        public virtual ActionResult Delete(int id = 0)
        {
            var entity = DbContext.Set<TEntityType>().Find(id);

            if (entity == null)
            {
                return HttpNotFound();
            }
            return View(entity);
        }

        [HttpPost, ActionName("Delete")]
        public virtual ActionResult DeleteConfirmed(int id)
        {
            var entity = DbContext.Set<TEntityType>().Find(id);
            DbContext.Set<TEntityType>().Remove(entity);
            DbContext.SaveChanges();
            return RedirectToAction("Index");
        }
    }
}
